package com.lehe.controller.admin;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.lehe.common.utils.StringUtil;
import com.lehe.dao.UserChargeGoldCoinLogDao;
import com.lehe.entry.*;
import com.lehe.entry.dbbean.GameUserDto;
import com.lehe.service.impl.AdminUserService;
import com.lehe.util.DateUtil;
import com.sun.tools.javac.code.Attribute.Array;
import com.sun.tools.javac.util.ArrayUtils;

import org.apache.poi.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lehe.dao.GoldDetailDao;
import com.lehe.dao.PayRecordDao;
import com.lehe.dao.UserInfoDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.entry.page.PageDto;
import com.lehe.service.impl.AdminFeeReportService;

@RequestMapping("admin/finance")
@Controller
public class FinanceController  extends BaseAdminController{

	@Autowired
	private UserManagerDao userManagerDao;
	@Autowired
	private GoldDetailDao goldDetailDao;
	@Autowired
	AdminFeeReportService adminFeeReportService;
	@Autowired
	private PayRecordDao payRecordDao;
	@Autowired
	AdminUserService adminUserService;
	@Autowired
	private UserChargeGoldCoinLogDao userChargeGoldCoinLogDao;

	/**
	 * 财务管理-用户查询
	 */
	@RequestMapping("userfinance")
	public String userfinance(Long userId,Long userType,Model m){

		m.addAttribute("userId",userId);
		m.addAttribute("userType",userType);
		return "admin/finance/info";
	}

	/**
	 * 财务管理-业绩查询
	 */
	@RequestMapping("score")
	public String score(Model m){
		List<Long> ids = this.getGameUserIds();
		
		if(ids != null && !ids.isEmpty()){
			m.addAttribute("ids",ids);
		}
		return "admin/finance/score/score";
	}
	
	@RequestMapping("scoreList")
	public String scoreList(String userId,String sd,String ed,Model m){
 		List<Long> userIds = null;
		if(StringUtil.isBlank(userId)){
			m.addAttribute("adminUser",this.getAdminUserSession());
			m.addAttribute("adminIds",this.getGameUserIds());
			m.addAttribute("adminIdsDisplay",this.getGameUserIds());
			userId = this.getAdminUserId().toString();
			userIds = this.getGameUserIds();
		}else{
			userIds = getUserIdsByAdmin(userId);
			if(!userIds.isEmpty()){
                AdminUserDto adminUserDto = adminUserService.queryByIdOrAccount(userId);
                m.addAttribute("adminUser",adminUserDto);
                m.addAttribute("adminIds",adminUserDto.getUserIds());
                if(adminUserDto.getUserIds() != null && adminUserDto.getUserIds().split(",").length > 0){
                	List<String> idstrs = new ArrayList<String>();
        			
        			for(String id : adminUserDto.getUserIds().split(",")){
        				idstrs.add(id.toString());
        			}
        			m.addAttribute("adminIdsDisplay",idstrs);
                }
            }
		}
		if(null == userIds || userIds.isEmpty()){
			m.addAttribute("noResrlt",true);
			return "admin/finance/score/scoreProfile";
		}
		String ownSum = userManagerDao.queryOwnChargeSumByIds(userIds, sd, ed);
		String ownCount = userManagerDao.queryOwnChargeSumByIdsCount(userIds, sd, ed);
		String playerSum =userManagerDao.queryPlayerChargeSumByIds(userIds, sd, ed);
		String agentSum = userManagerDao.queryAgentChargeSumByIds(userIds, sd, ed);
		m.addAttribute("ownSum",ownSum);
		m.addAttribute("ownCount",ownCount);
		m.addAttribute("playerSum",playerSum);
		m.addAttribute("agentSum",agentSum);
		m.addAttribute("goldSum",userManagerDao.queryAdminUserChargeSum(userId, sd, ed));

		return "admin/finance/score/scoreProfile";
	}
	
	@RequestMapping("score/loadOwnDetail")
	public String scoreLoadOwnDetail(String userId,String sd,String ed,Integer page,Integer pageSize,Model m){

		List<Long> ids = null;
		if(StringUtil.isBlank(userId)){
			ids = this.getGameUserIds();
		}else{
			ids = getUserIdsByAdmin(userId);
		}
		
		PageDto pd = new PageDto(page,pageSize);
		List<UserPayDetailDto> result = payRecordDao.queryUsersPayDetail(ids,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUsersPayDetailCount(ids,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		
		m.addAttribute("queryResult",result);
		return "admin/finance/score/myPayList";
	}
	
	@RequestMapping("score/loadPlayerDetail")
	public String scoreLoadOwnDetail(@RequestParam(required=false)String userId,
			@RequestParam(required=false)Integer page,
			String sd,String ed,
			@RequestParam(required=false)Integer pageSize,Model m){
		List<Long> ids = null;
		PageDto pd = new PageDto(page,pageSize);
		if(StringUtil.isBlank(userId)){
			ids = this.getGameUserIds();
		}else{
			ids = getUserIdsByAdmin(userId);
		}
		List<PlayerInfoDto> list = userManagerDao.queryUserPlayer(null,sd,ed,ids,pd.getPageIndex(),pd.getPageSize());
		Integer count = userManagerDao.queryUserPlayerCount(null,sd,ed,ids);
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/score/playerDetail";
	}
	@RequestMapping("score/loadAgentDetail")
	public String scoreLoadAgentDetail(@RequestParam(required=false)String userId, Long agentId,
			@RequestParam(required=false)Integer page,
			String sd,String ed,String orderBy,
			@RequestParam(required=false)Integer pageSize,Model m){
		List<MyAgentDto> list = null;
		Integer count = null;
		PageDto pd = new PageDto(page,pageSize);
		if(null!=agentId){
			//这个查询是要用agentId查询
			list = userManagerDao.queryUserAgent(null,agentId,sd,ed,null,orderBy,pd.getPageIndex(),pd.getPageSize());
			count = userManagerDao.queryUserAgentCount(null,agentId,sd,ed,null);
		}else{
			List<Long> ids = null;
			if(StringUtil.isBlank(userId)){
				ids = this.getGameUserIds();
			}else {
				ids = getUserIdsByAdmin(userId);
			}
			list = userManagerDao.queryUserAgentByIds(null,sd,ed, ids,null,orderBy, pd.getPageIndex(), pd.getPageSize());
			count = userManagerDao.queryUserAgentByIdsCount(null,sd,ed, ids,null);
		}
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/score/myAgentList";
	}

	@RequestMapping("score/loadGoldDetail")
	public String scoreLoadGoldDetail(@RequestParam(required=false)String userId,
									   @RequestParam(required=false)Integer page,
									   String sd,String ed,String orderBy,
									   @RequestParam(required=false)Integer pageSize,Model m){
		List<MyGoldDto> list = null;
		Integer count = null;
		PageDto pd = new PageDto(page,pageSize);
		if(StringUtil.isBlank(userId)){
			userId = this.getAdminUserId().toString();
		}
		list = userManagerDao.queryUserGold(userId,sd,ed,orderBy,pd.getPageIndex(),pd.getPageSize());
		count = userManagerDao.queryUserGoldCount(userId,sd,ed);
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/score/myGoldList";
	}
	
	@RequestMapping("userfinanceList")
	public String userfinanceList(Long userId,Long userType,String sd,String ed,Model m){
		String newed=ed;
		if(ed!=null && !"".equals(ed)){
			ed=DateUtil.addDay(ed);
		}
		m.addAttribute("userId",userId);
		m.addAttribute("userType",userType);
		if(userId==null){
			return "admin/finance/profile";
		}
		Long topId=this.getAdminUserId();
		if(1l == this.getAdminUserRoleId()){//如果是admin 就全部都查
			topId=null;
		}
		//查询用户基本信息
        List<UserGoldDetailDto> userDetailInfoList = goldDetailDao.queryUserDetailInfo(userId,userType,topId);		
        UserGoldDetailDto dto=null;
        if(userDetailInfoList!=null && userDetailInfoList.size()>0 && userDetailInfoList.get(0)!=null){
        	dto=userDetailInfoList.get(0);
        }else{
			return "admin/finance/profile";
		}
        //运营号不查询游戏信息
        if(dto.getUserType()==null || dto.getUserType()!=2){
	        //查询游戏胜负信息
			List<UserGoldDetailDto> userWinInfoList = goldDetailDao.queryUserWinInfo(userId, sd, ed);
			if(userWinInfoList!=null && userWinInfoList.size()>0){
				UserGoldDetailDto userWinInfo = userWinInfoList.get(0);
				dto.setWinCount(userWinInfo.getWinCount()==null?0:userWinInfo.getWinCount());
				dto.setWinSum(userWinInfo.getWinSum()==null?0:userWinInfo.getWinSum());
				dto.setDrawCount(userWinInfo.getDrawCount()==null?0:userWinInfo.getDrawCount());
				dto.setLostCount(userWinInfo.getLostCount()==null?0:userWinInfo.getLostCount());
				dto.setLostSum(userWinInfo.getLostSum()==null?0:userWinInfo.getLostSum());
				dto.setRevenue(userWinInfo.getRevenue()==null?"0":userWinInfo.getRevenue());
			}else{
				dto.setWinCount(0);
				dto.setWinSum(0);
				dto.setDrawCount(0);
				dto.setLostCount(0);
				dto.setLostSum(0);
				dto.setRevenue("0");
			}
			List<UserGoldDetailDto> countGiveScoreList = goldDetailDao.countGiveScore(userId, sd, ed);
			if(countGiveScoreList!=null && countGiveScoreList.size()>0){
				UserGoldDetailDto countGiveScore = countGiveScoreList.get(0);
				dto.setGiveScoreCount(countGiveScore.getGiveScoreCount()==null?0:countGiveScore.getGiveScoreCount());
				dto.setGiveScoreSum(countGiveScore.getGiveScoreSum()==null?0:countGiveScore.getGiveScoreSum());
			}else{
				dto.setGiveScoreCount(0);
				dto.setGiveScoreSum(0);
			}
			
			
        }
		//查询充值信息
		List<UserGoldDetailDto> countGoldDetailList = goldDetailDao.countGoldDetail(userId, sd, ed);
		if(countGoldDetailList!=null && countGoldDetailList.size()>0){
			UserGoldDetailDto countGoldDetail = countGoldDetailList.get(0);
			dto.setInCount(countGoldDetail.getInCount()==null?0:countGoldDetail.getInCount());
			dto.setInSum(countGoldDetail.getInSum()==null?0:countGoldDetail.getInSum());
			dto.setOutCount(countGoldDetail.getOutCount()==null?0:countGoldDetail.getOutCount());
			dto.setOutSum(countGoldDetail.getOutSum()==null?0:countGoldDetail.getOutSum());
			
			dto.setRebateSum(countGoldDetail.getRebateSum()==null?0:countGoldDetail.getRebateSum());
			dto.setRebateCount(countGoldDetail.getRebateCount()==null?0:countGoldDetail.getRebateCount());
			
		}else{
			dto.setInCount(0);
			dto.setInSum(0);
			dto.setOutCount(0);
			dto.setOutSum(0);
			dto.setRebateSum(0);
			dto.setRebateCount(0);
		}
		
		//查询金币明细
		List<UserGoldDetailDto> goldDetailList = goldDetailDao.selectGoldDetailByUserType(userId,dto.getUserType(), sd, ed,1,20);

		m.addAttribute("goldDetailList",goldDetailList);
		
		m.addAttribute("sd",sd);
		m.addAttribute("ed",newed);
		m.addAttribute("userData",dto);
		int count = goldDetailDao.selectGoldDetailCount(userId,dto.getUserType(), sd, ed);
		PageDto pd = new PageDto(1,20);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/profile";
	}
	
	@RequestMapping("userfinanceGoldDetail")
	public String userfinanceGoldDetail(@RequestParam(required=false)Long userId,Long userType,
									   @RequestParam(required=false)Integer page,
									   String sd,String ed,String orderBy,
									   @RequestParam(required=false)Integer pageSize,Model m){
		//查询金币明细
		List<UserGoldDetailDto> goldDetailList = goldDetailDao.selectGoldDetailByUserType(userId,userType, sd, ed,page,pageSize);

				m.addAttribute("goldDetailList",goldDetailList);
				
				m.addAttribute("sd",sd);
				m.addAttribute("ed",ed);
				int count = goldDetailDao.selectGoldDetailCount(userId,userType, sd, ed);
				PageDto pd = new PageDto(page,pageSize);
				pd.setRecordCount(count);
				m.addAttribute("page",pd);	
		return "admin/finance/myGoldDetailList";
	}
	
	@RequestMapping("userfinanceList/myPayList")
	public String userfinanceListmyPayList(Long userId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		List<UserPayDto> result = null;
		result = payRecordDao.queryUserPayDetail(userId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserPayDetailCount(userId,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		
		m.addAttribute("queryResult",result);
		return "admin/finance/myPayList";
	}
	
	@RequestMapping("userfinanceList/myPalayerList")
	public String userfinanceListmyPalayer(Long userId,Long agentId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		List<UserPayDto> result = payRecordDao.queryUserPlayerPayDetail(agentId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserPlayerPayDetailCount(agentId,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryResult",result);
		return "admin/finance/myPlayerList";
	}
	
	@RequestMapping("userfinanceList/myAgentList")
	public String userfinanceListmyAgentList(Long userId,Long agentId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		List<UserPayDto> result = payRecordDao.queryUserAngentPayDetail(agentId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserAngentPayDetailCount(agentId,sd,ed);
		//上级ID没有查询出来，再这里填充进去
		for(UserPayDto dto : result){
			dto.setGroupId(userId);
		}
		
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("group_userId",userId);
		m.addAttribute("group_agentId",agentId);
		m.addAttribute("queryResult",result);
		return "admin/finance/myAgentList";
	}

	private List<Long> getUserIdsByAdmin(String seachStr){
		List<Long> ret = new ArrayList<>();
		AdminUserDto adminUserDto = adminUserService.queryByIdOrAccount(seachStr);
		if (null == adminUserDto) {
			return ret;
		}
		if(StringUtil.isNotBlank(adminUserDto.getUserIds())){
			ret = Arrays.stream(adminUserDto.getUserIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
		}
		return ret;
	}

	@RequestMapping("dayReport")
	public String dayReportIndex(Model model){
		LocalDate today = LocalDate.now();
		model.addAttribute("startDate", today.with(TemporalAdjusters.firstDayOfMonth()));
		model.addAttribute("endDate", today);
		return "admin/finance/dayReport";
	}

	@RequestMapping("dayReportList")
	public String dayReportList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = adminFeeReportService.queryDayFeeReportCount(sqlParameterDto);
		List<FeeReportDto> list = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
		sqlParameterDto.setPageSize(null);
		sqlParameterDto.setPageSize(null);
		List<FeeReportDto> listAll = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		model.addAttribute("pageFeeSum",adminFeeReportService.sumFee(list));
		model.addAttribute("allFeeSum",adminFeeReportService.sumFee(listAll));
		model.addAttribute("pageGoldFeeSum",adminFeeReportService.sumGoldFee(list));
		model.addAttribute("allGoldFeeSum",adminFeeReportService.sumGoldFee(listAll));
		return "admin/finance/dayReportList";
	}

	@RequestMapping("monthReport")
	public String monthReport(Model model){
		LocalDate today = LocalDate.now();
		model.addAttribute("startDate", today.with(TemporalAdjusters.firstDayOfMonth()));
		model.addAttribute("endDate", today);
		return "admin/finance/monthReport";
	}

	@RequestMapping("monthReportList")
	public String monthReportList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = adminFeeReportService.queryMonthFeeReportCount(sqlParameterDto);
		List<FeeReportDto> list = adminFeeReportService.queryMonthFeeReport(sqlParameterDto);
		sqlParameterDto.setPageSize(null);
		sqlParameterDto.setPageSize(null);
		List<FeeReportDto> listAll = adminFeeReportService.queryMonthFeeReport(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		model.addAttribute("pageFeeSum",adminFeeReportService.sumFee(list));
		model.addAttribute("allFeeSum",adminFeeReportService.sumFee(listAll));
		model.addAttribute("pageGoldFeeSum",adminFeeReportService.sumGoldFee(list));
		model.addAttribute("allGoldFeeSum",adminFeeReportService.sumGoldFee(listAll));
		return "admin/finance/monthReportList";
	}

	@RequestMapping("queryPayDetail")
	public String queryPayDetail(Model model){
		return "admin/finance/queryPayDetail";
	}

	@RequestMapping("queryPayDetailList")
	public String queryPayDetailList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = payRecordDao.queryPayDetailCount(sqlParameterDto);
		List<UserPayDetailDto> list = payRecordDao.queryPayDetail(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		return "admin/finance/queryPayDetailList";
	}

	@RequestMapping("queryGoldDetail")
	public String queryGoldDetail(Model model){
		return "admin/finance/queryGoldDetail";
	}

	@RequestMapping("queryGoldDetailList")
	public String queryGoldDetailList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = userChargeGoldCoinLogDao.queryCountByUserId(sqlParameterDto);
		List<UserChargeGoldCoinLogDto> list = userChargeGoldCoinLogDao.queryListByUserId(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		return "admin/finance/queryGoldDetailList";
	}
	
}
